package io.mvvm.ws.handler;

import io.mvvm.ws.entity.RequestInfo;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @program: Netty
 * @description: 鉴权处理器
 * @author: 潘
 * @create: 2021-04-28 22:24
 **/
@Component
@ChannelHandler.Sharable
public class WebSocketAuthHandler extends ChannelInboundHandlerAdapter {

    public static final String HANDLER_NAME = "WebSocketAuthHandler";

    private static final Logger logger = LoggerFactory.getLogger(WebSocketAuthHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        RequestInfo msg = (RequestInfo) obj;
        // 如果鉴权失败，则关闭通道
        if (!msg.getUserId().equals("admin")) {
            logger.warn("鉴权未通过");
            ctx.channel().close();
            return;
        }

        msg.setUserId("ADMIN");

        // 热拔插鉴权处理器，如果鉴权通过了就不需要此处理器
        ctx.pipeline().remove(HANDLER_NAME);
        logger.info("授权通过");
        super.channelRead(ctx, msg);
    }

}
